//
//  JSONMgr.m
//  DoulinClient
//
//  Created by Apple on 15/2/5.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "JSONMgr.h"

@implementation JSONMgr

+ (id)getJsonDic:(NSData *)jsonData{
    NSError * error = nil;
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
    if (error){
        NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, error.localizedDescription);
        return nil;
    }
    return obj;
}
+ (NSString *)jsonStringFromObj:(id)obj{
    /** 转换成JSON的对象必须具有如下属性：
    1. 顶层对象必须是NSArray或者NSDictionary
    2. 所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull
    3. 所有NSDictionary的key必须是NSString类型
    4. 数字对象不能是非数值或无穷（NSNumber）
    */
    if ([NSJSONSerialization isValidJSONObject:obj]){
        NSError * error;
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&error];
        if(error){
            return nil;
        } else {
            NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            
            return jsonString;
        }
    } else {
        return nil;
    }

}
+ (NSDictionary *)dicFromJsonString:(NSString *)jsonString{
    if ([jsonString isKindOfClass:NSDictionary.class]) {
        return (NSDictionary *)jsonString;
    }
    if ((jsonString == nil) || [jsonString isKindOfClass:NSNull.class]) {
        return @{};
    }
    NSError * error;
    NSData * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers | NSJSONReadingAllowFragments error:&error];
    if (error) {
        NSLog(@"<-- %s, %d --> 解析失败: %@", __FUNCTION__, __LINE__, error);
        return @{};
    }
    return dic;
}

@end
